package com.atguigu.app;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.atguigu.constants.GmallConstants;
import com.atguigu.utils.MyKafkaSender;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Random;

public class CanalClient {
    public static void main(String[] args) throws InvalidProtocolBufferException {
        //1.创建连接对象
        CanalConnector canalConnector = CanalConnectors.newSingleConnector(new InetSocketAddress("hadoop102", 11111), "example", "", "");

        while (true) {
            //2.获取连接
            canalConnector.connect();

            //3.选择要获取数据的数据库
            canalConnector.subscribe("gmall210927.*");

            //4.获取Message对象
            Message message = canalConnector.get(100);

            //5.获取一条sql执行的结果
            List<CanalEntry.Entry> entries = message.getEntries();

            //6.判断是否有数据更新
            if (entries.size() > 0) {
                //有数据
                //7.遍历存放entry的list集合获取到每一个entry
                for (CanalEntry.Entry entry : entries) {
                    //TODO 8.获取表名
                    String tableName = entry.getHeader().getTableName();

                    //9.获取entry类型
                    CanalEntry.EntryType entryType = entry.getEntryType();

                    //10.判断entry类型是否为ROWDATA
                    if (CanalEntry.EntryType.ROWDATA.equals(entryType)) {
                        //11.获取序列化数据
                        ByteString storeValue = entry.getStoreValue();

                        //12.对数据做反序列化
                        CanalEntry.RowChange rowChange = CanalEntry.RowChange.parseFrom(storeValue);

                        //TODO 13.获取事件类型
                        CanalEntry.EventType eventType = rowChange.getEventType();

                        //TODO 14.获取多行数据
                        List<CanalEntry.RowData> rowDatasList = rowChange.getRowDatasList();

                        //单独创建方法来获取具体某个表中的某种类型数据
                        handler(tableName, eventType, rowDatasList);
                    }
                }

            } else {
                try {
                    System.out.println("没有数据，休息一会！！！！！");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void handler(String tableName, CanalEntry.EventType eventType, List<CanalEntry.RowData> rowDatasList) {
        //获取订单表中新增的数据
        if ("order_info".equals(tableName) && CanalEntry.EventType.INSERT.equals(eventType)) {
            saveTokafka(rowDatasList, GmallConstants.KAFKA_TOPIC_ORDER);
        } else if ("order_detail".equals(tableName) && CanalEntry.EventType.INSERT.equals(eventType)) {
            saveTokafka(rowDatasList, GmallConstants.KAFKA_TOPIC_ORDER_DETAIL);
        } else if ("user_info".equals(tableName) && (CanalEntry.EventType.INSERT.equals(eventType) || CanalEntry.EventType.UPDATE.equals(eventType))) {
            saveTokafka(rowDatasList, GmallConstants.KAFKA_TOPIC_USER);

        }
    }

    private static void saveTokafka(List<CanalEntry.RowData> rowDatasList, String kafkaTopicOrder) {
        //获取每一行的数据
        for (CanalEntry.RowData rowData : rowDatasList) {
            List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
            JSONObject jsonObject = new JSONObject();
            //获取每一行中每一列
            for (CanalEntry.Column column : afterColumnsList) {
                jsonObject.put(column.getName(), column.getValue());
            }
            System.out.println(jsonObject.toString());
            //模拟网络震荡
           /* try {
                Thread.sleep(new Random().nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            //将数据发送至Kafka
            MyKafkaSender.send(kafkaTopicOrder, jsonObject.toString());
        }
    }
}
